package com.ryan.time.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Note;

import com.ryan.util.LogUtil;

public class DbContentProvider extends ContentProvider {

	private static final String TAG = "DbContentProvider";

	private DbHelper mDbHelper;
	private SQLiteDatabase mDb;
	private UriMatcher mUriMatcher;

	private static final int CODE_TIME = 100;
	private static final int CODE_TIME_ID = 101;

	@Override
	public boolean onCreate() {
		mDbHelper = new DbHelper(getContext());
		mDb = mDbHelper.getWritableDatabase();

		mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mUriMatcher.addURI("com.ryan.time.provider", "time", CODE_TIME);
		mUriMatcher.addURI("com.ryan.time.provider", "time/#", CODE_TIME_ID);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		int code = mUriMatcher.match(uri);
		switch (code) {
		case CODE_TIME:
			return mDb.query("time", projection, selection, selectionArgs,
					null, null, sortOrder);
		default:
			LogUtil.w(TAG, "no match" + uri);
		}
		return null;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		int code = mUriMatcher.match(uri);
		switch (code) {
		case CODE_TIME:
			long id = mDb.insert("time", null, values);
			this.getContext().getContentResolver()
					.notifyChange(DbHelper.Time.CONTENT_URI, null);
			return ContentUris.withAppendedId(uri, id);
		default:
			LogUtil.w(TAG, "no match" + uri);
			return null;
		}
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int code = mUriMatcher.match(uri);
		switch (code) {
		case CODE_TIME_ID:
			return mDb.delete("time", DbHelper.Time.ID+"=?",
					new String[] { ContentUris.parseId(uri) + "" });
		default:
			LogUtil.w(TAG, "no match" + uri);
		}

		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int code = mUriMatcher.match(uri);
		switch (code) {
		case CODE_TIME_ID:
			return mDb.update("time", values, DbHelper.Time.ID+"=?",
					new String[] { ContentUris.parseId(uri) + "" });
		default:
			LogUtil.w(TAG, "no match" + uri);
		}

		return 0;
	}

}
